// pages/buyMenberCard/buyMenberCard.js
var app = getApp()
Page({
  data: {
    current:0,
    showCardIntroduce: false,  //显示会员卡权益和使用说明
    currentCard:{},
	orderfenlei:'all_0',
    payType: '1',
    hadCardRight:true,
    hadCardNotice: true,
    page: 0,
	level_id:0,
    noMoretip: false,
	sellevel_id:0,
	levelnum:0,
	user_type:0,
	memberShop:[],
	selectIds:[],
	totoalwight:0,
	lessnum:'2500'
  },
  onLoad: function (e) {
    var that = this;
    app.setVersion(that);
    wx.getSystemInfo({
      success: function(res) {
        console.log(res)
        var x = res.windowWidth - 80;
        var y = res.windowHeight - 70;
        that.setData({
          x: x,
          y: y,
          showBtn:true
        })
      },
    })
  },
  onShow: function () {
	  var that=this;
	  that.setData({
	  	memberShop:[],
	  	levelnum:0,
	  	totoalwight:0,
	  	lessnum:2500,
	  	selectIds:[]
	  })
	  that.requestMember();
  },
  //获得当前的日期
  getCurrentDate: function () {
    var that = this;
    var myDate = new Date();
    //获取当前年
    var year = myDate.getFullYear();
    //获取当前月
    var month = myDate.getMonth() + 1;
    //获取当前日
    var day = myDate.getDate();
    var str = year + '-' + month + '-' + day;
    that.setData({
      date: str
    });
    console.log(that.data.date);
  },
  tobuyzhuanqu:function(e){
	 wx.navigateTo({
	   url: '/pages/waitBuyLevel/waitBuyLevel'
	 })
  },
  shopchangernum:function(e){
		var that=this;
		console.log(e);
		var type = e.currentTarget.dataset.type;
		var id = e.currentTarget.dataset.id;
		var number = e.currentTarget.dataset.number;
		var goodslist =that.data.memberShop;
		var allnum=0;
		if(type==1){
			var stock =e.currentTarget.dataset.stock;
			if (number >= stock) {
				wx.showToast({
				  icon:'none',
				  title: '库存不足',
				})
				return false;
			}
			number =number + 1;
		}else{
			if (number <= 0) {
				return false;
			}
			number = number - 1;
		}		
		for (let i = 0; i < goodslist.length; i++) {
			if(id ==goodslist[i]['id']){
				goodslist[i]['number'] =number;
			}
			allnum+=goodslist[i]['number'];
		}		
		if(allnum>10){
			wx.showToast({
			  icon:'none',
			  title: '单次领取限购10份',
			})
			for (let i = 0; i < goodslist.length; i++) {
				if(id ==goodslist[i]['id']){
					goodslist[i]['number']--;
				}
			}	
			allnum=allnum-1;
		}
		var selectIds=[];
		for(let m=0;m<goodslist.length;m++){
			if(goodslist[m]['number']>0){
				selectIds[m] =goodslist[m];
			}
		}
		
		that.setData({
			memberShop:goodslist,
			levelnum:allnum,
			totoalwight:allnum*250,
			lessnum:2500-allnum*250,
			selectIds:selectIds
		})
  },
  allgetGoods:function(e){
	var that=this;
	if(that.data.levelnum<10){
		  wx.showToast({
		    icon:'none',
		    title: '请选择领取10份商品',
		  })
		  return false;
	}
	//发起请求，获取列表列表
	wx.showToast({
	  title: '加载中',
	  icon: 'loading',
	  mask: true,
	  duration: 10000
	});
	wx.request({
	    url: app.globalData.requestUrl,
	    data: {
	      map: 'applet_store_level_order',
		  level_id:that.data.level_id,
		  buys:that.data.selectIds
	    },
	    success: function (res) {
			
	        if (res.data.ec == 200) {
	            wx.setStorage({
				   key: "submitOrder",
				   data: res.data.data,
				   success: function (res) {
					 that.setData({					 	
					 	levelnum:0,
					 	selectIds:[]
					 })					 
					 wx.navigateTo({
					   url: '/pages/waitBuyerPay/waitBuyerPay'
					 })
				   }
	            })
		    }else{
				console.log(res.data.em);
				wx.showToast({
				  icon:'none',
				  title:res.data.em,
				})
			}
		}
	})
  },
  //获得所填信息
  getUserInfor: function () {
    var that = this;
    wx.request({
      url: app.globalData.requestUrl,
      data: {
        map: 'applet_store_member_info',
      },
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data);
          that.setData({
            name: res.data.data.name,
            sexValue: res.data.data.gender ? res.data.data.gender : '1',
            date: res.data.data.birthday,
            telphone: res.data.data.telphone,
            coin: res.data.data.coin
          })
        } else {
          console.log(res.data)
        }
      },
      complete: function () {
        // wx.hideLoading();
      }
    });
  },
  //获得支付方式
  radioChange: function (e) {
    var that = this;
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    that.setData({
      payType: e.detail.value
    })
  },
  sexSelect: function (e) {
    var that = this;
    var sex = e.currentTarget.dataset.sex;
    that.setData({
      sexValue: sex
    })
  },
  nameChange: function (e) {
    var that = this;
    that.setData({
      name: e.detail.value
    })
    console.log(that.data.name);
  },
  phoneChange: function (e) {
    var that = this;
    console.log('电话');
    console.log(e.detail.value);
    that.setData({
      telphone: e.detail.value
    })
    console.log(that.data.telphone);
  },
  submitInfor: function () {
    var that = this;
    app.getSubId(that, 'applet_buy_member_card', 'toSubmitInfor');
  },
  toSubmitInfor: function () {
    var that = this;
    if (!that.data.currentCard.levelCanBuy){
      app.errorTip(that, "不能降级购买会员卡", 2000);
      return
    }
    var data = {};
    var id = that.data.currentCard.id;
    var type = that.data.currentCard.type;
    var name = that.data.name;
    var gender = that.data.sexValue;
    var birthday = that.data.date;
    var telphone = that.data.telphone;
    var payType = that.data.payType;
    data.map = 'applet_buy_member_card';
    data.cardid = id;
    data.type = type;
    data.name = name;
    data.gender = gender;
    data.birthday = birthday;
    data.telphone = telphone;
    data.payType = payType;
    console.log(data);
    if (!data.telphone) {
      app.errorTip(that, "请输入手机号码", 2000);
      return;
    }
    wx.showModal({
      title: '提示',
      content: '确认立即支付吗？',
      success(result) {
        if (result.confirm) {
          wx.showLoading({
            title: '加载中',
          })
          wx.request({
            url: app.globalData.requestUrl,
            data: data,
            success: function (res) {
              if (res.data.ec == 200) {
                console.log(res.data.data);
                if (res.data.data.status == 'dzf') {
                  that.orderPay(res.data.data.tid);
                } else if (res.data.data.status == 'zfcg') {
                  wx.showToast({
                    icon:'success',
                    title: '支付成功',
                    success(){
                      setTimeout(function () {
                        wx.navigateBack({
                          delta: 1
                        })
                      }, 1500)
                    }
                  })
                  
                }
              } else {
                console.log(res.data);
                wx.hideLoading();
                app.errorTip(that, res.data.em, 2000);
              }
            },
            complete: function () {
              // wx.hideLoading();
            }
          });
        } else if (result.cancel) {
          console.log('用户点击取消')
        }
      }
    })
  },
  levelitemId:function(e){
	  var that=this;
	  var id = e.currentTarget.dataset.id;
	  if(id==0){
		    wx.showToast({
				icon: 'none',
				title: '请选择专区类型',
		   })
		   return;
	  }else{
		  that.setData({
		    level_id: id
		  })
	  }
  },
  chooseFenlei: function (e) {
	console.log(e)
    var that = this;
    that.setData({
      memberShop: null,
      classstyle: 'active',
	  selectIds:[],
	  levelnum:0,
      page: 0,
	  current:e.currentTarget.dataset.index,
	  sellevel_id:e.currentTarget.dataset.id,
      noMoretip: false,
      showLoading: true
    })
    that.requestMember(e.currentTarget.dataset.id);
  },
  openMemberLevelPay:function(e){
	  var that=this;
	  var data = {};
	  data.map = 'applet_pay_member_userlevel';
	  data.level_id = that.data.level_id;
	  console.log(data);
	  if(data.level_id==0){
		  wx.showToast({
			icon: 'none',
			title: '请选择专区类型',
		  })
		  return;
	  }
	  //发起请求，获取列表列表
	  wx.showToast({
	    title: '加载中',
	    icon: 'loading',
	    mask: true,
	    duration: 1000
	  });
	  wx.request({
	    url: app.globalData.requestUrl,
	    data: data,
	    success: function (res) {
			if (res.data.ec == 200) {
			  console.log(res.data.data);
			  wx.requestPayment({
			    'appId': res.data.data.appId,
			    'timeStamp': res.data.data.timeStamp,
			    'nonceStr': res.data.data.nonceStr,
			    'package': res.data.data.package,
			    'signType': res.data.data.signType,
			    'paySign': res.data.data.paySign,
			      success: function (res) {
			      wx.showToast({
			        icon: 'success',
			        title: '支付成功',
			        success() {
			          setTimeout(function () {
			            wx.navigateBack({
			              delta: 1
			            })
			          }, 1500)
			        },
			      })
			    },
			    fail: function (res) {
			      wx.showToast({
			        icon: 'none',
			        title: '支付失败',
			      })
			      console.log(res); 
			    }
			  });
			} else {
			  wx.showToast({
			    icon: 'none',
			    title: res.data.em,
			  })			  
			}
		},
	 })
  },
  orderPay: function (tid) {
    var that = this;
    var data = {};
    data.map = 'applet_pay_member_card';
    data.tid = tid;
    console.log(data);
    //发起请求，获取列表列表
    wx.showToast({
      title: '加载中',
      icon: 'loading',
      mask: true,
      duration: 1000
    });
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        if (res.data.ec == 200) {
          console.log(res.data.data);
          wx.requestPayment({
            'appId': res.data.data.appId,
            'timeStamp': res.data.data.timeStamp,
            'nonceStr': res.data.data.nonceStr,
            'package': res.data.data.package,
            'signType': res.data.data.signType,
            'paySign': res.data.data.paySign,
              success: function (res) {
              wx.showToast({
                icon: 'success',
                title: '支付成功',
                success() {
                  setTimeout(function () {
                    wx.navigateBack({
                      delta: 1
                    })
                  }, 1500)
                },
              })
            },
            fail: function (res) {
              wx.showToast({
                icon: 'none',
                title: '支付失败',
              })
              console.log(res); 
            }
          });
        } else {
          wx.hideToast();
          console.log(res.data);
          app.errorTip(that, res.data.em, 2000);
        }
      },
      complete: function () {
        
      }
    });
  },
  openMemberRecord:function(){
    var that =  this;
    wx.navigateTo({
      url: '/subpages/memberRecord/memberRecord',
    })
  },
  // 会员卡介绍
  openCardIntroduce() {
    this.setData({
      showCardIntroduce: true
    })
  },
  closeCardIntroduce() {
    this.setData({
      showCardIntroduce: false
    })
  },
  //得到当前swiper的current值
  getCurrent:function(e){
    var that = this;
    console.log(e.detail);
    that.setData({
      current: e.detail.current,
      currentCard: this.data.cardList[e.detail.current]
    });
  },
  changeCurrent:function(e){
    var that = this;
    var type = e.currentTarget.dataset.type;
    var current = that.data.current;
    if(type=='prev'){
      if (current>0){
        current--;
      }
    }else if(type=='next'){
      if (current < that.data.cardList.length - 1){
        current++;
      }
    }
    that.setData({
      current: current,
      currentCard: this.data.cardList[e.detail.current]
    })
  },
  prevCard:function(){
    var that = this;
    var current = that.data.current;
    if (current==0){
      current = 1
    }else{
      current--;
    }
    console.log(current)
    that.setData({
      current: current
    });
  },
  nextCard: function () {
    var that = this;
    var current = that.data.current;
    if (current == 1) {
      current = 0
    }else{
      current++;
    }
    console.log(current)
    that.setData({
      current: current
    });
  },
  // 新接口获取专区等级以及等级商品
  requestMember: function (level_id) {
    var that = this;
    var data = {};
    data.map = 'applet_userlevel_list';
	data.level_id =level_id;
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: app.globalData.requestUrl,
      data: data,
      success: function (res) {
        console.log(res);
        if (res.data.ec == 200) {
          var memCard = res.data.data;
          var goods = res.data.goods;
		  var level_id =res.data.level_id;
		 
		 that.setData({
		   memCard: memCard,    //会员卡片信息
		   memberShop : goods,
		   level_id : level_id,		 			
		 })
		 
		 
		  var data = {};
		  data.map = 'applet_userlevel_Info';
		  data.level_id =level_id;
		  wx.request({
			  url: app.globalData.requestUrl,
			  data: data,
			  success: function (ress) {
			    console.log(ress);
			    if (ress.data.ec == 200) {
					var user_type =ress.data.user_type
					that.setData({
					  user_type:user_type
					})
				}
			 }
		  })
		  
        }
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    })
  },
  //跳转商品列表页
  goshopList: function (e) {
    var that = this;
    console.log(e);
    var id = e.currentTarget.dataset.id;
    var title = e.currentTarget.dataset.name;
    if (that.data.isVip) {
      wx.navigateTo({
        url: '/subpages0/wnGoodsList/wnGoodsList?id=' + id + "&title=" + title,
      })
    } else {
      wx.showToast({
        title: '请先开通会员！',
        icon: 'none',
      })
    }

  },
  //跳转商品详情
  toshopDetail: function (e) {
    var that = this;
    console.log(e);
    var id = e.currentTarget.dataset.id;
    if (that.data.isVip) {
      wx.navigateTo({
        url: '/pages/goodDetail/goodDetail?id=' + id,
      })
    } else {
      wx.showToast({
        title: ' 请先开通会员！',
        icon: 'none',
      })
    }

  },
  //下拉刷新
  onReachBottom: function () {
    
  }
})